//
//  BookingHotelController.swift
//  AirTravel
//
//  Created by apple on 2021/7/21.
//

import UIKit
import FWPopupView
import HandyJSON
class BookingHotelController: UIViewController {
    
    @IBOutlet weak var topLine: NSLayoutConstraint!
    @IBOutlet weak var tabView: UITableView!
    /// 标题
    @IBOutlet weak var titleLab: UILabel!
    let identifyST = "ScheduledTimeCell"
    let identifyRRC = "ReservationRequiredCell"
    let identifyID = "InDetailsCell"
    let identifyCPC = "CheckPersonCell"
    let identifyP = "PromptCell"
    
    
    @IBOutlet weak var sumLabel: UILabel!
    
    
    var order_id = ""
    var payType = ""
    var time1 = ""
    var time2 = ""
    var cityId = ""
    var hotelId = ""
    var scoreArray = [""]
    
    var hotelDetail:CityHotelMianModel?
    
    var hotelDetailList:CityHotelDetailModel?
    
    
    var passengersArray = [Dictionary<String,Any>]()
    
    
    lazy var hotelViewModel: HotelFacilitiesViewModel = {
        let iconView = HotelFacilitiesViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if SCREEN_WIDTH >= 812 {
            self.topLine.constant = 88
        }else{
            self.topLine.constant = 64
        }
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.separatorStyle = .none
        self.tabView.estimatedRowHeight = 147
        self.tabView.rowHeight = UITableView.automaticDimension
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "ScheduledTimeCell", bundle: nil), forCellReuseIdentifier: identifyST)
        self.tabView.register(UINib.init(nibName: "ReservationRequiredCell", bundle: nil), forCellReuseIdentifier: identifyRRC)
        self.tabView.register(UINib.init(nibName: "InDetailsCell", bundle: nil), forCellReuseIdentifier: identifyID)
        self.tabView.register(UINib.init(nibName: "CheckPersonCell", bundle: nil), forCellReuseIdentifier: identifyCPC)
        self.tabView.register(UINib.init(nibName: "PromptCell", bundle: nil), forCellReuseIdentifier: identifyP)
        
        sumLabel.text = "￥ " + hotelDetailList!.minprice
    }


    @IBAction func backBtn(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func subClick(_ sender: UIButton) {
        NetWorkRequest(API1.hotelAvail(parameters: ["roomId":self.hotelDetailList?.roomInfo?.first?.roomID ?? "" ,"checkInDate":self.time1,"checkOutDate":self.time2,"hotelId":self.hotelId , "ratePlanCategory" : self.hotelDetailList?.roomInfo?.first?.roomPriceInfo?.ratePlanCategory ?? "" ,"quantity" : "\(hotelViewModel.currentTag)","guestCount" : passengersArray.count,"lateArrivalTime" : "\(self.time1) 14:00" , "supplierId" : self.hotelDetailList?.roomInfo?.first?.supplierId ?? ""]), completion: {[weak self] (responseString) -> (Void) in
           guard let model = JSONDeserializer<hotelAvailModel>.deserializeFrom(json: "\(responseString["data"])") else {
               return
               
           }
            
//            if(!model.canBook){
//                YProgressHUD.showToast("不可预定")
//                return
//            }
//
//            if(model.availableQuantity == 0){
//                YProgressHUD.showToast("房间不足")
//                return
//            }
            
            self?.createDD()
            

       }, failed: { (failedResutl) -> (Void) in
           print("服务器返回code不为0000啦~\(failedResutl)")
       }, errorResult: { () -> (Void) in
           print("网络异常,超时")
       })
    }
    
    
    func createDD(){
        
        var arr :[Int] = []
        
        for item in passengersArray{
            if item.isEmpty == false {
                let num:Int = item["id"] as! Int
                arr.append(num)
               
            }
        }
        
        
        let cell = tabView.cellForRow(at: IndexPath(row: 0, section: 4)) as! PromptCell
        
        
        NetWorkRequest(API1.createHotelOrder( parameters: ["passengers" : arr,"mobile" : "\(cell.phontTf.text ?? "")","unitPrice" : self.hotelDetailList?.minprice ?? "","cityId" : cityId,"roomId":self.hotelDetailList?.roomInfo?.first?.roomID ?? "" ,"checkInDate":self.time1,"checkOutDate":self.time2,"hotelId":self.hotelId , "ratePlanCategory" : self.hotelDetailList?.roomInfo?.first?.roomPriceInfo?.ratePlanCategory ?? "" ,"quantity" : "\(hotelViewModel.currentTag)","bookNumber" : passengersArray.count,"lateArrivalTime" : "\(self.time1) 14:00" , "supplierId" : self.hotelDetailList?.roomInfo?.first?.supplierId ?? ""]), completion: {[weak self] (responseString) -> (Void) in
           guard let model = JSONDeserializer<createHotelOrderModel>.deserializeFrom(json: "\(responseString["data"])") else {
               return
               
           }
            self?.order_id = model.order_id
            self?.payView.show()

       }, failed: { (failedResutl) -> (Void) in
           print("服务器返回code不为0000啦~\(failedResutl)")
       }, errorResult: { () -> (Void) in
           print("网络异常,超时")
       })
        
    }
    
    func payFunc(order_id:String){
        
         NetWorkRequest(API1.orderPay(parameters: ["order_id":order_id,"method":"app"]), completion: {[weak self] (responseString) -> (Void) in
            if self?.payType == "4"{
                //调起微信支付
                let req = PayReq.init()
                req.partnerId = "\(responseString["data"]["partnerid"])"
                req.prepayId = "\(responseString["data"]["prepayid"])"
                req.nonceStr = "\(responseString["data"]["noncestr"])"
                req.timeStamp = UInt32("\(responseString["data"]["timestamp"])") ?? 0
                req.package = "\(responseString["data"]["package"])"
                req.sign = "\(responseString["data"]["sign"])"
                WXApi.send(req, completion: nil)
            }else{
                //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
                let appScheme = "AirTravel"
                
                // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
                let orderString = responseString["data"].stringValue
                
                // NOTE: 调用支付结果开始支付
                AlipaySDK.defaultService()?.payOrder(orderString, fromScheme: appScheme, callback: { (resultDic) in
                    
                    print("afafa")
                })
            }
            
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
        
    }
    
    
    lazy var payView: ChoosePayView = {
        let customPopupView = ChoosePayView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 320))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.white
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "0"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
}

extension BookingHotelController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int{
        return 5
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 3:
            return self.passengersArray.count + 1
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyST) as! ScheduledTimeCell
            let timeDate = stringFormatToDate(timeString: time1, format: "yyyy-MM-dd")
            
            let timeDate1 = stringFormatToDate(timeString: time2, format: "yyyy-MM-dd")
            
            
            
            let formatter = DateFormatter()
            let calendar = Calendar.current
            formatter.dateFormat = "yyyy-MM-dd"
           
            let diff:DateComponents = calendar.dateComponents([.day], from: timeDate!, to: timeDate1!)

            
            getTwoDate(date: timeDate, date1: timeDate1) { [weak self] result in
                print("**********\(result)")
                
                cell.ydTimeLab.text = result[0].0 + "-" + result[1].0 +
                    "共\(diff.day ?? 0)晚"
             
            }
            
            cell.tagLab.text = hotelDetail?.hotelName
            cell.serviceLab.text = hotelDetailList?.roomInfo?.first?.roomBedTypeInfo?.roomBedName
            cell.quTimeLab.text = hotelDetailList?.roomInfo?.first?.cancelLimitInfo?.cancelPolicyInfo
            cell.selectionStyle = .none
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyRRC) as! ReservationRequiredCell
            cell.contentLab.text = hotelDetailList?.roomInfo?.first?.promotionInfo?.text
            cell.selectionStyle = .none
            return cell
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyID) as! InDetailsCell
            cell.promptLab.text = "每间最多可入住\(hotelDetailList?.roomInfo?.first?.person ?? "")人"
            cell.selectionStyle = .none
            self.hotelViewModel.bindViewToViewModel(collView: cell.collView, number: 2)
            self.hotelViewModel.closure = { tag in
                let str = Int(self.hotelDetailList!.minprice)
                self.sumLabel.text = "￥ " + "\(2 * str!)"
            }
            return cell
        case 4:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyP) as! PromptCell
            
            cell.contentLab.text = hotelDetailList?.roomInfo?.first?.promotionInfo?.text
            cell.selectionStyle = .none
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyCPC) as! CheckPersonCell
            cell.chooseBtn.addTarget(self, action: #selector(addPerson), for: .touchUpInside)
            if(self.passengersArray.count != 0){
                if(indexPath.row > (self.passengersArray.count - 1)){
                    cell.inputTf.text = ""
                    return cell
                }
                let dic = self.passengersArray[indexPath.row]
                cell.inputTf.text = "\(dic["name"] ?? "")"
            }
   
            cell.selectionStyle = .none
            return cell
            
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.section {
        case 0,1,4:
            return UITableView.automaticDimension
        case 2:
            return 140
        default:
            return 50
        }
    }
}




extension BookingHotelController:HotelFacilitiesDelegate{
    func hotelFacilitiesClick(data: NSDictionary) {
        
    }
    
    
   @objc func addPerson(){
        let vc = SelectPassengersController()
        vc.identity_type = "10"
        vc.delegate = self
        vc.mutArray = self.passengersArray
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}


extension BookingHotelController:SelectPassengersDelegate{
    func selectPassengersClick(array: [Dictionary<String,Any>]) {
        self.passengersArray = array
        
        var dicArr = [Dictionary<String,Any>]()
        
        for item in array {
            if item.isEmpty == false {
                dicArr.append(item)
               
            }
        }
        
        self.passengersArray = dicArr
        self.tabView.reloadData()
    }
}

extension BookingHotelController:ChoosePayDelegate{
    func choosePayClick(data: Dictionary<String, Any>) {
        self.payView.hide()
        self.payView.hideKeyboard()
        let key = "\(data["key"] ?? "")"
        self.payType = key
        self.payFunc(order_id: order_id)
    }
}

